<template>
  <div class="playVideo-layout">
    <!-- 播放器 -->
    <div id="app-container" class="video-box">
      <video
        ref="videoElement"
        :src="videoUrl"
        id="videoElement"
        controls
        muted
        :style="{width: `${width}px`, height: `${height}px`}">
      </video>
    </div>
  </div>
</template>
<script>
import hlsjs from "hls.js";
export default {
  name: "hls",
  components: {},
  data () {
    return {};
  },
  props: {
    videoUrl: {
      default: ``
    },
    width: {
      default: 400,
    },
    height: {
      default: 300,
    }
  },
  watch: {
    videoUrl (nval, vold) {
      console.log(nval, vold);
    }
  },
  mounted () {
    setTimeout(_ => {
      this.show();
    }, 2000);
    
  },
  methods: {
    //播放
    show () {
      this.video = this.$refs.videoElement; //定义挂载点
      if (hlsjs.isSupported()) {
        this.hlsjs = new hlsjs();
        this.hlsjs.loadSource(this.videoUrl);//设置播放路径
        this.hlsjs.attachMedia(this.video);//解析到video标签上

        this.hlsjs.on(hlsjs.Events.MANIFEST_PARSED, () => {
          this.video.play();
          console.log("加载成功");
        });
        this.hlsjs.on(hlsjs.Events.ERROR, (event, data) => {
          //   console.log(event, data);
          // 监听出错事件
          console.log("加载失败");
        });
      } else {
        this.$message.error("不支持的格式");
        return;
      }
    },
    //停止播放
    closeVideo () {
      if (this.hlsjs) {
        this.$refs.videoElement.pause();
        this.video.pause();
        this.hlsjs.destroy();
        this.hlsjs = null;
        this.$emit("closeVideo");
      }
    },
  },
  computed: {},
  watch: {},
  filters: {},
};
</script>
<style lang="scss" scoped>
  .playVideo-layout {
    display: inline-block;
    width: 600px;
    #videoElement {
      object-fit: fill;
    }
  }
</style>